﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WPS.Log;
using WPS.SDK.http;
using WPS.SDK.model.yunfile;
using WPS.SDK.openapi;

namespace WPS.SDK.openapi
{
    public class YunFile
    {
        #region 获取APP剩余空间
        /// <summary>
        /// 获取APP剩余空间
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static RemainingSpace getRemainingSpace(string accessToken)
        {
            string url = Config.getOpenApiServer() + "/oauthapi/v2/appfile/remaining?appid=" + Config.getAppid() + "&access_token=" + accessToken;
            return RemainingSpace.fromJsonObject(new Request().Get(url).getJSONObject());
        }
        #endregion

        #region 获取文件列表
        /// <summary>
        /// 获取文件列表（可选参数不需要传null即可）
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="parentid"></param>
        /// <param name="order"></param>
        /// <param name="orderby"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static FileList getAppFileList(string accessToken, string parentid, string order, string orderby, string offset, string count)
        {
            string requestUrl = Config.getOpenApiServer() + "/oauthapi/v3/app/files/list?appid=" + Config.getAppid() + "&access_token=" + accessToken + "&open_parentid=" + parentid;
            if (!string.IsNullOrEmpty(order))
            {
                requestUrl = requestUrl + "&order=" + order;
            }
            if (!string.IsNullOrEmpty(orderby))
            {
                requestUrl = requestUrl + "&order_by=" + orderby;
            }
            if (!string.IsNullOrEmpty(offset))
            {
                requestUrl = requestUrl + "&offset=" + offset;
            }
            if (!string.IsNullOrEmpty(count))
            {
                requestUrl = requestUrl + "&count=" + count;
            }
            LogHelper.Info(requestUrl);
            return FileList.fromJsonObject(new Request().Get(requestUrl).getJSONObject());
        }
        #endregion

        #region 创建文件夹
        public static CreateFolder createFolder(string accessToken, string parentid, string name)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", accessToken);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("open_parentid", parentid);
            jsonObject.Add("name", HttpUtility.HtmlEncode(name));
            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/folders/create";
            return CreateFolder.fromJsonObject(new Request().Post(url, jsonString).getJSONObject());
        }
        #endregion

        #region 上传文件

        public static FileInfo uploadFile(string accessToken, long parentid, HttpPostedFileBase file)
        {
            UploadUrlData uploadUrlData = getUploadUrl(accessToken, parentid, file.ContentLength, file.FileName);
            string sha1 = upload2CDN(uploadUrlData, file);
            return uploadFileInfo(accessToken, parentid, file.ContentLength, sha1, file.FileName);

        }
        #endregion

        #region 获取文件下载链接
        public static FileDownloadUrl getFileDowloadUrl(string accessToken, string fileid)
        {
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/files/download/url?appid=" + Config.getAppid() + "&access_token=" + accessToken + "&open_fileid=" + fileid;
            return FileDownloadUrl.fromJsonObject(new Request().Get(url).getJSONObject());
        }
        #endregion

        #region 文件重命名
        public static FileRename fileRename(String accessToken, String fileid, String newname)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", accessToken);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("open_fileid", fileid);
            jsonObject.Add("new_name", newname);
            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/files/rename";
            return FileRename.fromJsonObject(new Request().Post(url, jsonString).getJSONObject());

        }
        #endregion

        #region 文件复制
        public static FileCopyInApp fileCopyInApp(string accessToken, string fileids, string fromParentid, string toParentid)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", accessToken);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("open_fileids", fileids);
            jsonObject.Add("open_from_parentid", fromParentid);
            jsonObject.Add("open_to_parentid", toParentid);

            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/files/copy";
            return FileCopyInApp.fromJsonObject(new Request().Post(url, jsonString).getJSONObject());
        }
        #endregion

        #region 文件移动
        public static FileMoveInApp fileMoveInApp(String accessToken, String fileids, String fromParentid, String toParentid)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", accessToken);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("open_fileids", fileids);
            jsonObject.Add("open_from_parentid", fromParentid);
            jsonObject.Add("open_to_parentid", toParentid);
            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/files/move";
            return FileMoveInApp.fromJsonObject(new Request().Post(url, jsonString).getJSONObject());
        }
        #endregion

        #region 文件删除
        public static FileDelete fileDelete(String accessToken, String fileids)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", accessToken);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("open_fileids", fileids);

            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/files/delete";
            return FileDelete.fromJsonObject(new Request().Delete(url, jsonString).getJSONObject());
        }
        #endregion


        #region 搜索文件ByName
        public static FileList serchByName(string accessToken, string parentid, string fname, string offset, string count)
        {
            string requestUrl = Config.getOpenApiServer() + "/oauthapi/v3/app/files/searchbyname?appid=" + Config.getAppid() + "&access_token=" + accessToken + "&file_name=" + fname + "&open_parentid=" + parentid;
            if (offset != null)
            {
                requestUrl = requestUrl + "&offset=" + offset;
            }
            if (count != null)
            {
                requestUrl = requestUrl + "&count=" + count;
            }
            return FileList.fromJsonObject(new Request().Get(requestUrl).getJSONObject());
        }
        #endregion

        #region  搜索文件ByContent
        public static FileList serchByContent(string accessToken, string parentid, string content, string offset, string count)
        {
            string requestUrl = Config.getOpenApiServer() + "/oauthapi/v3/app/files/searchbycontent?appid=" + Config.getAppid() + "&access_token=" + accessToken + "&content=" + content + "&open_parentid=" + parentid;
            if (offset != null)
            {
                requestUrl = requestUrl + "&offset=" + offset;
            }
            if (count != null)
            {
                requestUrl = requestUrl + "&count=" + count;
            }
            return FileList.fromJsonObject(new Request().Get(requestUrl).getJSONObject());
        }

        #endregion

        #region 创建文件
        public static CreateFile createFile(string accessToken, string parentid, string name, bool addNameIndex)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", accessToken);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("open_parentid", parentid);
            jsonObject.Add("file_name", name);
            jsonObject.Add("add_name_index", addNameIndex);

            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v3/app/files/create";
            return CreateFile.fromJsonObject(new Request().Post(url, jsonString).getJSONObject());
        }
        #endregion

        #region 获取上传路径

        private static UploadUrlData getUploadUrl(string accessToken, long parentid, long size, string name)
        {
            string url = Config.getOpenApiServer() + "/oauthapi/v2/files/upload/url?appid=" + Config.getAppid() + "&access_token=" + accessToken + "&parentid=" + parentid.ToString() + "&size=" + size.ToString() + "&name=" + HttpUtility.HtmlEncode(name);
            return UploadUrlData.fromJsonObject(new Request().Get(url).getJSONObject());
        }

        #endregion

        #region 获取文件上传参数
        private static string upload2CDN(UploadUrlData uploadUrlData, HttpPostedFileBase file)
        {
            HttpWebRequest request = WebRequest.Create(uploadUrlData.upload_url) as HttpWebRequest;
            request.Method = "PUT";
            request.ContentType = uploadUrlData.content_type;
            request.Date = Convert.ToDateTime(uploadUrlData.date);
            request.Headers.Add("x-kss-newfilename-in-body", uploadUrlData.x_kss_newfilename_in_body);
            request.Headers.Add("authorization", uploadUrlData.authorization);
            return new Request().Put(request, file).getString("newfilename");
        }
        #endregion

        #region 上传文件信息
        private static FileInfo uploadFileInfo(String access_token, long parentid, long size, string sha1, string name)
        {
            JObject jsonObject = new JObject();
            jsonObject.Add("access_token", access_token);
            jsonObject.Add("appid", Config.getAppid());
            jsonObject.Add("parentid", parentid);
            jsonObject.Add("size", size);
            jsonObject.Add("sha1", sha1);
            jsonObject.Add("name", HttpUtility.HtmlEncode(name));
            string jsonString = JsonConvert.SerializeObject(jsonObject);
            string url = Config.getOpenApiServer() + "/oauthapi/v2/files/upload";
            return FileInfo.fromJsonObject(new Request().Post(url, jsonString).getJSONObject());
        }
        #endregion

        #region 获取分享文件链接
        public static LinkInfo getFileLinkInfo(string accessToken, string fileid, string permission, string period)
        {
            string requestUrl = Config.getOpenApiServer() + "/oauthapi/v3/app/files/link?appid=" + Config.getAppid() + "&access_token=" + accessToken + "&open_fileid=" + fileid;
            if (permission != null)
            {
                requestUrl += "&permission=" + permission;
            }
            if (period != null)
            {
                requestUrl += "&period=" + period;
            }
            return LinkInfo.fromJsonObject(new Request().Get(requestUrl).getJSONObject());
        }

        #endregion


    }
}
